/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#if 0
#include "maya_local.h"

#include "../etc/rapidxml/rapidxml_ext.hpp"
#include "../etc/rapidxml/rapidxml_print.hpp"
using namespace rapidxml;

const char *ProjectVersion(void);

const uint LEVEL_MESH_FORMAT = GE_MESH_POSITION | GE_MESH_COLOR_0 | GE_MESH_NORMAL | GE_MESH_UV_0;


/*-----------------------------------------------------------------------------
	Maya Level Exporter :
-----------------------------------------------------------------------------*/

//
//	EMLevelExporter::WalkDAG
//
EMLevelExporter::EMLevelExporter()
{
	
}


//
//	EMLevelExporter::WalkDAG
//
EMLevelExporter::~EMLevelExporter()
{
}


//
//	EMLevelExporter::WalkDAG
//
MStatus EMLevelExporter::writer(const MFileObject &file, const MString &optionsString, MPxFileTranslator::FileAccessMode mode)
{
	HardRef<ELevelAssembler>	level = new ELevelAssembler();

	if (mode == MPxFileTranslator::kExportActiveAccessMode) {
		MGlobal::displayWarning("Level exporter must work with entire scene");
		return MStatus::kFailure;
	}

	string	path = file.fullName().asChar();
	LOG_SPLIT(va("Level export : %s", path.c_str()));
	
		//
		//	Parse hierarchy :
		//
		//	get root path :
		MItDag		dag_iter(MItDag::kDepthFirst, MFn::kTransform);
		MFnDagNode	root_node( dag_iter.root() );
		MDagPath	dag_path;
		MAYA_CALL( root_node.getPath( dag_path ) );

		LOGF("Parsing : DAG hierarchy\r\n");
		MAYA_CALL( ParseHierarchy( level->GetRoot(), dag_path, 0 ) );		


		//
		//	Preprocess level and write XML :
		//
		level->Process();
		level->WriteXML(path.c_str());


	LOG_SPLIT("");

	return MStatus::kSuccess;
}



static EMatrix4	Matrix4ExtractScaleMatrix( const EMatrix4 &M ) 
{
	//EMatrix4 M2 = Matrix4Inverse( M );
	EVec3	x_axis	=	EVec3( M(0,0), M(1,0), M(2,0) );
	EVec3	y_axis	=	EVec3( M(0,1), M(1,1), M(2,1) );
	EVec3	z_axis	=	EVec3( M(0,2), M(1,2), M(2,2) );
	float	sx		=	Vec3Length( x_axis );
	float	sy		=	Vec3Length( y_axis );
	float	sz		=	Vec3Length( z_axis );
	
	return Matrix4Scale( sx, sy, sz );
}


//
//	EMLevelExporter::ParseHierarchy
//
MStatus EMLevelExporter::ParseHierarchy( IPxLvNode lv_node, MDagPath node_path, uint depth )
{
	MStatus status;
	
	MObject	node = node_path.node();

	//
	//	Setup transformation for current node :
	//	NOTE : root node does not have transform
	//	
	if (depth!=0) {
		//	check transform node :	
		ASSERT( node.hasFn(MFn::kTransform) );

		ParseTransform( lv_node, node );
	} 
	
	//
	//	Iterate over all child :	
	//
	for (uint i=0; i<node_path.childCount(); i++) 
	{
		MObject		child		=	node_path.child(i);
		MDagPath	child_path	=	node_path;
		child_path.push( child );	// extend path to child

		//	skip these objects :
		if (child_path.fullPathName()=="|groundPlane_transform"	)	continue;
		if (child_path.fullPathName()=="|Manipulator1"			)	continue;
		if (child_path.fullPathName()=="|UniversalManip"		)	continue;
		if (child_path.fullPathName()=="|CubeCompass"			)	continue;
		if (child_path.fullPathName()=="|persp"					)	continue;
		if (child_path.fullPathName()=="|top"					)	continue;
		if (child_path.fullPathName()=="|front"					)	continue;
		if (child_path.fullPathName()=="|side"					)	continue;

		//		
		//	Child is a locator, add entity desc :
		//
		if (child.hasFn(MFn::kLocator)) {
			MAYA_CALL( ParseLocatorNode( lv_node, child ) );
			continue;
		}

		//		
		//	Child is a mesh :
		//
		if (child.hasFn(MFn::kMesh)) {
			MFnDagNode dag_mesh(child);
			//	skip intermediate meshes, such as bool operands etc.
			if (dag_mesh.isIntermediateObject()) {
				continue;
			}
			
			lv_node->mesh	=	ge()->CreateTriMesh( LEVEL_MESH_FORMAT );
			
			MAYA_CALL( ParseMesh( lv_node->mesh, child, child_path ) );

			lv_node->mesh->Transform( lv_node->scale );
			lv_node->scale = Matrix4Identity();
			
			continue;
		}


		//
		//	Child is a tranform node, 
		//	continue recursive descending :
		//
		if (child.hasFn(MFn::kTransform)) 
		{
			IPxLvNode	lv_child_node = new ELvNode();
			lv_node->AddNode(lv_child_node);
		
			MAYA_CALL( ParseHierarchy(lv_child_node, child_path, depth+1) );
			continue;
		}
	}
	
	return MS::kSuccess;
}


/*-----------------------------------------------------------------------------
	Locator :
-----------------------------------------------------------------------------*/

//
//	EMLevelExporter::ParseLocatorNode
//
MStatus EMLevelExporter::ParseLocatorNode( IPxLvNode lv_node, MObject &obj )
{
	MStatus status;

	MFnDependencyNode	dnode(obj);		//	get dependency node from current MObject
	MFnTypedAttribute		fn_typed;
	MFnNumericAttribute		fn_numeric;
	MFnCompoundAttribute	fn_compound;
	
	//	NOTE : Look "cgfxAttrDef.cpp" to get how to parse node's atributes.
			
	for (uint i=0; i<dnode.attributeCount(); i++) {

		MObject attr = dnode.attribute(i);
		MPlug	attr_plug(obj, attr);

		//	remove object name: "object.attribute" -> "attribute" :
		MString attr_name	=	attr_plug.name();
		MString key			=	attr_name.substring( attr_name.index('.')+1, attr_name.length());
		//LOGF("[%s]\r\n", skey.asChar());

		//	Compound attribute (color or vector) :
		//if ( fn_compound.setObject(attr) ) 
		//{
		//	MString key	=	attr_plug.name();
		//	EVec4	vec4(0,0,0,0);
		//	uint  num = fn_compound.numChildren();
		//	num = Clamp<uint>(num, 0, 4);
		//	
		//	for (uint j=0; j<num; j++) {
		//		vec4.v[j] = attr_plug.child(j).asFloat();
		//	}

		//	lv_node_ent->SetValue( key.asChar(), va("%g  %g  %g  %g ", vec4.x, vec4.y, vec4.z, vec4.w) );
		//} 
		//else
		//
		////	Numberic attribute :
		//if ( fn_numeric.setObject(attr) ) 
		//{
		//	MString key	=	attr_plug.name();
		//	float fval	=	attr_plug.asFloat();
		//	
		//	lv_node_ent->SetValue( key.asChar(), va("%g ", fval) );
		//} 
		//else
		
		//	'elv_bbox' - is a vector value 
		//	and it will not be parsed as string attribute :
		if (key=="elv_bbox") {
			EVec4	bbox = Maya_ReadVector(obj, attr, EVec4(0,0,0,1));
			lv_node->entity_desc.SetValue( "bbox", va("%g  %g  %g ", bbox.x, bbox.y, bbox.z));
		} else

		//		
		//	String attribute :
		if ( fn_typed.setObject(attr) && fn_typed.attrType() == MFnData::kString) 
		{
			MString	value	=	"";
			attr_plug.getValue(value);
			
			if (key.substring(0,3)=="elv_") {
				key = key.substring(4, key.length()-1);
				lv_node->entity_desc.SetValue( key.asChar(), value.asChar() );
			}
		} 
		else {	
			// unrecognizable attribute type
		}
	}
	

	return MStatus::kSuccess;
}

#endif

